<?php
namespace frontend\models;

use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{

    public $tel;

    public $email;
    
    public $rpassword;
    
    public $code;

    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['tel','trim'],
            [['tel','password','rpassword','code'],'required'],
            [
                'tel',
                'unique',
                'targetClass' => '\common\models\User',
                'message' => '手机号已被注册'
            ],
            [
                'tel','match','pattern'=>'/^[1][358][0-9]{9}$/'
            ],
            [
                'code',
                'integer'
            ],
            ['rpassword','compare','compareAttribute'=>'password','message'=>'两次密码输入不一致。'],
            [
                'password',
                'string',
                'min' => 6
            ]
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (! $this->validate()) {
            return null;
        }
        
        $user = new User();
        $user->username='rf'.uniqid().rand(100, 999);
        $user->tel = $this->tel;
        $user->email = $this->email;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        
        return $user->save() ? $user : null;
    }
    public function attributeLabels(){
        return [
            'tel'=>'手机号',
            'password'=>'密码',
            'code'=>'验证码',
            'rpassword'=>'确认密码'
        ];
    }
}
